package main

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"go-small-shopping/router"
	"time"
)

type CustomClam struct {
	*jwt.StandardClaims
	UserName string
	Password string
}

func main() {
	g := router.Router()
	err := g.Run(":8085")
	if err != nil {
		return
	}

	//tokenString, err := generateJWT("admin", "123456")
	//if err != nil {
	//	fmt.Println(err)
	//}
	//fmt.Println(tokenString)
	//claim, err := validateJWT(tokenString)
	//if err != nil {
	//	fmt.Println(err)
	//}
	////claim json打印
	//fmt.Println(claim)

}

func generateJWT(usrer string, pwd string) (string, error) {
	exp := time.Now().Add(time.Hour * 2).Unix()
	claim := CustomClam{
		UserName: usrer,
		Password: pwd,
		StandardClaims: &jwt.StandardClaims{
			ExpiresAt: exp,
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
	secretKey := []byte("1066e1e8a49275706e9e8e88967f63ebae7c4629543e53c769c448706ff5b614")

	tokenString, err := token.SignedString(secretKey)

	if err != nil {
		return "", err
	}
	return tokenString, nil
}

func validateJWT(tokenString string) (*CustomClam, error) {
	secretKey := []byte("1066e1e8a49275706e9e8e88967f63ebae7c4629543e53c769c448706ff5b614")

	token, err := jwt.ParseWithClaims(tokenString, &CustomClam{}, func(token *jwt.Token) (interface{}, error) {
		return secretKey, nil
	})
	if err != nil {
		return nil, err
	}
	if claims, ok := token.Claims.(*CustomClam); ok && token.Valid {
		return claims, nil
	}
	return nil, fmt.Errorf("invalid token")
}
